import {connect} from '@umijs/max'
import { useEffect,useMemo ,useRef, useState} from 'react'
import {ActionType,ProTable,PageContainer,ProDescriptionsItemProps} from '@ant-design/pro-components'
import { Button, Divider, Tag ,Popconfirm, message} from 'antd'
import { PlusOutlined, FormOutlined} from '@ant-design/icons'
import { StaffService } from '@/services/staff'
import CreateForm from './components/CreatForm'
import UpdateForm from './components/UpdateForm'



//离职处理
const dismissHandler=async(record:API.StaffInfo)=>{
    const hide=message.loading('正在离职');
    try{
        await StaffService.dismissStaff(record.stf_id)
        hide()
        message.success(`员工:"${record.stf_name}"离职成功`)
        return true
    }catch(error){
        hide()
        message.error(`员工:"${record.stf_name}"离职失败,请稍后重试`);
        return false
    }
}
//复职处理
const reinstateHandler = async (record: API.StaffInfo) => {
  const hide = message.loading('正在复职');
  try {
    await StaffService.reinstateStaff(record.stf_id);
    hide();
    message.success(`员工:"${record.stf_name}"复职成功`);
    return true;
  } catch (error) {
    hide();
    message.error(`员工:"${record.stf_name}"复职失败,请稍后重试`);
    return false;
  }
};
//新增处理
const addHandler=async(fields:API.Staff_Add_Body)=>{
    const hide=message.loading('正在添加');
    try{
        await StaffService.addStaff({...fields})//为啥结构加点
        hide()
        message.success(`员工:"${fields.stf_name}"添加成功`)
        return true
    }catch(error){
        hide()
        message.error(`员工:"${fields.stf_name}"添加失败,请稍后重试`);
        return false
    }
}
//修改处理
const updateHandler = async (fields: API.Staff_Modify_Body) => {
    const hide=message.loading('正在修改');
    try{
        await StaffService.modifyStaff({...fields})
        hide()
        message.success(`员工:"${fields.stf_name}"编辑成功`);
        return true
    }
    catch(error){
        hide()
        message.error(`员工:"${fields.stf_name}"编辑失败,请稍后重试`);
        return false
    }
};
//定义组件
const StaffPage: React.FC = ({staffCategoryList,dispatch}) => {
    const actionRef=useRef<ActionType>()
    const [createModalVisible, setCreateModalVisible]=useState<boolean>(false)
    const [updateModalVisible, setUpdateModalVisible]=useState<boolean>(false)
    const [echoStaff,setEchoStaff]=useState({})
    useEffect(() => {
        dispatch({type:'dic/init'})
    },[])
    const staffCategoryEnum = useMemo(() => {
        const result=new Map()
        result.set(0,{text:'-请选择-'})
        staffCategoryList.forEach(item => result.set(item.dic_id,{text:item.dic_name}))
        return result
        // const result={0:{text:'-请选择-'}}
        // staffCategoryList.forEach(item => result[item.dic_id] = {text:item.dic_name})
        // return result
    },[staffCategoryList])
    const columns: ProDescriptionsItemProps<API.StaffInfo>[] = [
      {
        title: '序号',
        dataIndex: 'index',
        valueType: 'indexBorder',
        align: 'center',
        width: 60,
      },
      {
        title:'',
        dataIndex:'stf_id',
        hideInSearch:true,
        hideInTable:true,
        formItemProps:{
            hidden:true//不在表单中显示，但仍然会搜集和校验字段，点击提交时仍然会被汇总起来
        }
      },
      {
        title: '员工姓名',
        dataIndex: 'stf_name',
        initialValue: '',
        formItemProps: {
          rules: [
            { required: true, message: '员工姓名为必填项' },
            { min: 2, max: 10, message: '员工名字长度在2-10之间' },
          ],
        },
      },
      {
        title: '员工岗位',
        dataIndex: 'stf_category',
        initialValue: 0,
        valueEnum: staffCategoryEnum,
        formItemProps: {
          rules: [
            {
              validator: (_, value) =>
                value !== 0 ? Promise.resolve() : Promise.reject(new Error('请选择员工岗位')),
            },
          ],
        },
      },
      {
        title: '在职状态',
        hideInSearch: true,
        hideInForm: true,
        render: (_, record) =>
          record.stf_invalid === 0 ? (
            <Tag color="#bfc1c6">离职</Tag>
          ) : (
            <Tag color="green">在职</Tag>
          ),
      },
      {
        title: '员工备注',
        dataIndex: 'stf_remark',
        hideInSearch: true,
        valueType: 'textarea',
        initialValue: '',
      },
      {
        title: '操作',
        dataIndex: 'option',
        hideInSearch: true,
        hideInForm: true,
        render: (_, record) => (
          <>
            <Button
              type="primary"
              icon={<FormOutlined />}
              onClick={() =>{ 
                setEchoStaff({...record})
                setUpdateModalVisible(true)
               }}
            >
              编辑
            </Button>
            <Divider type="vertical" />
            {record.stf_invalid === 0 ? (
              <Popconfirm
                title={`你确定要："${record.stf_name}"复职吗？`}
                onConfirm={async () => {
                  const success = await reinstateHandler(record);
                  if (success) actionRef.current?.reloadAndRest?.(); //和reload有啥区别
                }}
                onCancel={() => message.info('你取消了复职操作')}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <Button type="dashed">复职</Button>
              </Popconfirm>
            ) : (
              <Popconfirm
                title={`你确定要："${record.stf_name}"离职吗？`}
                onConfirm={async () => {
                  const success = await dismissHandler(record);
                  if (success) actionRef.current?.reloadAndRest?.();
                }}
                onCancel={() => message.info('你取消了离职操作')}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <Button danger>离职</Button>
              </Popconfirm>
            )}
          </>
        ),
      },
    ];
    const proTableProps = {
      cardBordered: true,
      bordered: true,
      headerTitle:'员工列表',
      search:{searchText:'搜索',resetText:'重置'},
      actionRef:actionRef,
      pagination: {pageSize: 10},
      toolBarRender:()=><Button type='primary' icon={<PlusOutlined />} onClick={()=>setCreateModalVisible(true)}>新增</Button>,
      rowKey: 'stf_id',
      columns: columns,
      request: async (params) => {
        const { current, pageSize, stf_name, stf_category } = params;
        const { list, total } = await StaffService.queryStaffList({
          pageSize: params.pageSize,
          begin: (params.current - 1) * params.pageSize,
          stf_name: params.stf_name,
          stf_category: params.stf_category,
        });
        return {
          data: list,
          success: true,
          total: total,
        };
      },
    };

    return (
      <PageContainer ghost>
        <ProTable<API.StaffInfo> {...proTableProps} />
        <CreateForm
          onCancel={() => setCreateModalVisible(false)}
          modalVisible={createModalVisible}
        >
          <ProTable<API.StaffInfo, API.StaffInfo>
            onSubmit={async (fields) => {
              const success = await addHandler(fields);
              if (success) {
                setCreateModalVisible(false);
                actionRef.current?.reload?.();
              }
            }}
            rowKey="stf_id"
            type="form"
            columns={columns}
          />
        </CreateForm>
        <UpdateForm
          onCancel={() => setUpdateModalVisible(false)}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.StaffInfo, API.StaffInfo> //两个API.StaffInfo是干啥的
            onSubmit={async (fields) => {
              const success = await updateHandler(fields);
              if (success) {
                setUpdateModalVisible(false);
                actionRef.current?.reload?.();
              }
            }}
            rowKey="stf_id"
            type="form"
            form={{initialValues:echoStaff}}
            columns={columns}
          />
        </UpdateForm>
      </PageContainer>
    );
}
const mapModelToProps = state => ({
  staffCategoryList:state.dic.list.filter(item => item.dic_group_key === 'staff_category'),
});

export default connect(mapModelToProps) (StaffPage)